<template>
	<view class="address_form">
		<view class="form_item">
			<text class="label">收货人：</text>
			<input type="text" placeholder="请填写收货人姓名" class="ipt" v-model="addressForm.name">
		</view>
		<view class="form_item">
			<text class="label">手机号码：</text>
			<input type="number" placeholder="请填写收货人手机号码" class="ipt" v-model="addressForm.phone">
		</view>
		<view class="form_item">
			<text class="label">所在地区：</text>
			<text class="select" @click="show = true" v-if="!addressForm.area_name">请选择所在地区</text>
			<text class="select" @click="show = true" v-else style="color: #000;">{{addressForm.area_name}}</text>
			<u-picker :show="show" ref="uPicker" title="请选择" :closeOnClickOverlay="true" :columns="columns"
				@confirm="confirm" @change="changeHandler" @cancel="cancel" @close="cancel">
			</u-picker>
		</view>
		<view class="form_item">
			<text class="label">详细地址：</text>
			<input type="" placeholder="请填写详细地址" class="ipt" v-model="addressForm.desc">
		</view>
		<view class="form_item">
			<text style="padding-left:10px;padding-right: 20px;">设为默认地址</text>
			<u-switch v-model="isDefault" @change="change" activeColor="#884e22" size="20"></u-switch>
		</view>
		<view class="submit" @click="save">
			保存
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				show: false,
				edit_id: 0,
				// 默认城市
				columns: [],
				cityLevel1: [],
				cityLevel2: [],
				cityLevel3: [],
				addressForm: {
					name: '',
					phone: '',
					area: '',
					area_name: '',
					desc: '',
				},
				isDefault: false,
				reg_tel: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
			}
		},
		computed: {
			...mapState('userInfo', ['userInfo']),
			...mapState('city', ['cityList'])
		},
		onLoad(options) {
			if (options.id !== "undefined") {
				this.edit_id = options.id
				this.addressForm.name = options.name
				this.addressForm.phone = options.phone
				this.addressForm.area = options.area
				this.addressForm.area_name = options.area_name
				this.addressForm.desc = options.desc
				this.isDefault = options.default_set === '1' ? true : false
			}
			this.initCityData()
		},
		methods: {
			// 处理数据
			initCityData() {
				this.cityList.forEach((item1, index1) => {
					let temp2 = [];
					let temp4 = [];
					let temp3 = [];
					this.cityLevel1.push(item1.cityname);
					// 遍历市
					item1.children.forEach((item2, index2) => {
						temp2.push(item2.cityname);
						if (item2.children) {
							// 遍历区
							item2.children.forEach((item3) => {
								temp3.push(item3.cityname)
							})
							temp4[index2] = temp3;
							temp3 = [];
						}
					})
					this.cityLevel3[index1] = temp4;
					this.cityLevel2[index1] = temp2;
				})
				// 选择器默认城市
				this.columns.push(this.cityLevel1, this.cityLevel2[0], this.cityLevel3[0][0]);
			},
			changeHandler(e) {
				const {
					columnIndex,
					index,
					indexs,
					value,
					values,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				if (columnIndex === 0) { // 选择第一列数据时
					// 设置第二列关联数据
					picker.setColumnValues(1, this.cityLevel2[index]);
					// 设置第三列关联数据
					picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
				} else if (columnIndex === 1) { // 选择第二列数据时
					// 设置第三列关联数据
					if (this.cityLevel3[indexs[0]][index]) {
						picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
					} else {
						picker.setColumnValues(2, []);
					}
				}
			},
			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				let province;
				let city;
				let county;
				this.show = false
				e.value.forEach((ele, index) => {
					if (index === 0) {
						if (ele === '北京' || ele === '天津' || ele === '上海' || ele === '重庆') {
							this.addressForm.area_name = `${ele}市`
						} else if (ele === '香港' || ele === '澳门') {
							this.addressForm.area_name = `${ele}特别行政区`
						} else if (ele === '新疆' || ele === '内蒙古' || ele === '宁夏' || ele === '广西' || ele === '西藏') {
							this.addressForm.area_name = `${ele}自治区`
						} else {
							this.addressForm.area_name = `${ele}省`
						}
						province = this.cityList.find((item) => item.cityname === ele)
						this.addressForm.area = province.id
					} else if (index === 1) {
						if (ele === '市辖区') {
							this.addressForm.area_name += ` 北京市 `
						} else {
							this.addressForm.area_name += ` ${ele}市 `
						}
						city = province.children.find((item) => item.cityname === ele)
						this.addressForm.area += `,${city.id}`
					} else {
						this.addressForm.area_name += ele
						county = city.children.find((item) => item.cityname === ele)
						this.addressForm.area += `,${county.id}`
					}
				})
			},
			cancel() {
				this.show = false
			},
			change() {
				console.log(this.isDefault);
			},
			save() {
				if (this.addressForm.name === '') {
					this.error('请填写收货人姓名')
				} else if (this.addressForm.phone === '') {
					this.error('请填写收货人手机号码')
				} else if (this.addressForm.area_name === '') {
					this.error('请选择所在地区')
				} else if (this.addressForm.desc === '') {
					this.error('请填写详细地址')
				} else if (!this.reg_tel.test(this.addressForm.phone)) {
					this.error('请填写正确的手机号')
				} else {
					if (this.edit_id) {
						uni.$http.put(`/api/address/${this.edit_id}`, {
							...this.addressForm
						}).then(res => {
							if (this.isDefault) {
								uni.$http.post(`/api/setDefault/${res.data.result.id}`)
							}
							uni.navigateBack()
						})
					} else {
						uni.$http.post('/api/address', {
							...this.addressForm,
							password: this.userInfo.password
						}).then(res => {
							if (this.isDefault) {
								uni.$http.post(`/api/setDefault/${res.data.result.id}`)
							}
							this.$refs.uToast.show({
								type: 'success',
								message: '保存成功',
								duration: 500,
								position: "top",
								complete() {
									uni.navigateBack()
								}
							})
						})
					}

				}

			},
			// 表单验证错误触发
			error(text) {
				this.$refs.uToast.show({
					type: 'error',
					message: text,
					duration: 1000,
					position: "top",
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address_form {
		height: 100vh;
		background-color: #f1f1f1;

		.form_item {
			display: flex;
			align-items: center;
			background-color: #fff;
			// font-size: 14px;
			padding: 12px 0;
			border-top: 1px solid #f1f1f1;

			.label {
				width: 25%;
				padding-left: 10px;
			}

			.select {
				color: #888;
			}
		}

		.submit {
			background-color: #884e22;
			color: #fff;
			line-height: 42px;
			text-align: center;
			border-radius: 21px;
			width: 70%;
			margin: 30px auto;
		}
	}
</style>